package com.example.demoface.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demoface.domian.User;
import com.example.demoface.mapper.UserMapper;
import com.example.demoface.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> selectUser(User user) {

        List<User> users = userMapper.selectUsers(user);
        return users;
    }

    @Override
    public int deleteByUserId(String userId) {
        redisTemplate.delete("user_id:" + userId);
        User user = new User();
        user.setUserId(userId);
        return userMapper.deleteById(user);
    }

    @Override
    public int insertUser(User user) {
        int insert = userMapper.insert(user);
        return insert;
    }

    @Override
    public User selectOneByTele(String tele) {
        return userMapper.selectOneUserByTele(tele);
    }

    @Override
    public User selectOneById(String userId) {
        redisTemplate.opsForValue().increment("count_user_id:" + userId);
        // user_id:121212
        Object o = redisTemplate.opsForValue().get("user_id:" + userId);
        if(o != null){ // 判断是否在缓存中
            User user = JSONObject.parseObject(o.toString(),User.class);
             // 是
            return user;
        }
        else {
            User user = userMapper.selectById(userId); // 查数据库
            redisTemplate.opsForValue().set("user_id:" + user.getUserId(), user); //跟新缓存
            return user;
        }
    }

    @Override
    public User selectUsersWithDept(User user) {
        return userMapper.selectUsersWithDept(user);
    }


}
